<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>APK构建工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .upload-section {
            margin-bottom: 20px;
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        .button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }
        .status {
            margin-top: 20px;
            padding: 10px;
            border-radius: 4px;
        }
        .success {
            background-color: #dff0d8;
            color: #3c763d;
        }        
        .error {
            background-color: #f2dede;
            color: #a94442;
        }
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.4);
        }
        .modal.show {
            display: block;
        }
        .modal-content {
            background-color: #fefefe;
            margin: 15% auto;
            padding: 20px;
            border: 1px solid #888;
            width: 300px;
            border-radius: 5px;
        }
        .login-form input {
            width: 100%;
            padding: 8px;
            margin: 8px 0;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .log-window {
            position: fixed;
            right: 20px;
            bottom: 20px;
            width: 400px;
            background: white;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            resize: both;
            overflow: auto;
            min-width: 300px;
            min-height: 200px;
            cursor: move;
        }
        .log-window .header {
            padding: 5px;
            cursor: move;
            background: #f5f5f5;
            margin: -10px -10px 10px -10px;
            padding: 10px;
            border-bottom: 1px solid #ddd;
        }
        .log-content {
            height: calc(100% - 50px);
            overflow-y: auto;
            background-color: #f5f5f5;
            padding: 10px;
            font-family: monospace;
            white-space: pre-wrap;
            font-size: 12px;
            resize: none;
        }
    </style>
</head>
<body>    
    <div id="loginModal" class="modal">
        <div class="modal-content">
            <h2>登录</h2>
            <div class="login-form">
                <input type="text" id="username" placeholder="用户名">
                <input type="password" id="password" placeholder="密码">
                <button class="button" onclick="login()">登录</button>
            </div>
            <div id="loginStatus" class="status"></div>
        </div>
    </div>
    
    <div class="container">
        <h1>对外的 离线包 APK构建工具</h1>
        
        <div class="upload-section">
            <h2>上传聊天 debug 离线包 dist 包</h2>
            <input type="file" id="chatPackageDebug" webkitdirectory directory>
            <button class="button" onclick="uploadChatPackage('debug')">点击上传</button>
        </div>

        <div class="upload-section">
            <h2>上传聊天 release 离线包 dist 包</h2>
            <input type="file" id="chatPackageRelease" webkitdirectory directory>
            <button class="button" onclick="uploadChatPackage('release')">点击上传</button>
        </div>

        <div class="upload-section">
            <h2>上传人车生活 debug 离线包 dist 包</h2>
            <input type="file" id="carlifePackageDebug" webkitdirectory directory>
            <button class="button" onclick="uploadCarlifePackage('debug')">点击上传</button>
        </div>

        <div class="upload-section">
            <h2>上传人车生活 release 离线包 dist 包</h2>
            <input type="file" id="carlifePackageRelease" webkitdirectory directory>
            <button class="button" onclick="uploadCarlifePackage('release')">点击上传</button>
        </div>          
        <div class="build-section">
            <div>
                <button class="button" id="buildDebugButton" onclick="buildApk('debug')">构建 测试APK</button>
                <button class="button" id="buildReleaseButton" onclick="buildApk('release')">构建 正式APK</button>
                <!-- <button class="button" id="unBuildButton" onclick="unBuildApk('debug')">取消构建所有APK</button> -->
            </div>
            <div style="margin-top: 10px;">
                <button class="button" onclick="downloadApk('debug')">下载 测试APK</button>
                <button class="button" onclick="downloadApk('release')">下载 正式APK</button>
            </div>
        </div>

        <div id="status" class="status"></div>        <div class="log-window">
            <div class="header">构建日志</div>
            <div id="logContent" class="log-content"></div>
        </div>
    </div>    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.0.1/socket.io.js"></script> -->
    <script src="{{ url_for('static', filename='socket.io.js') }}"></script>
    <script>
        let chatPackageUploaded = false;
        let carlifePackageUploaded = false;

        // 页面加载完成后检查登录状态
        document.addEventListener('DOMContentLoaded', function() {
            const isLoggedIn = {{ 'true' if logged_in else 'false' }};
            if (!isLoggedIn) {
                document.getElementById('loginModal').classList.add('show');
            }
        });

        // 连接WebSocket
        const socket = io();
        const logContent = document.getElementById('logContent');

        // 接收日志消息
        socket.on('log_message', function(msg) {
            logContent.innerHTML += msg.data + '\n';
            logContent.scrollTop = logContent.scrollHeight;
        });


        function showStatus(message, isError = false) {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = message;
            statusDiv.className = 'status ' + (isError ? 'error' : 'success');
        }

        // 获取操作锁
        async function acquireLock(operation) {
            try {
                const response = await fetch('/acquire_lock', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ operation })
                });
                const data = await response.json();
                if (!data.success) {
                    alert(`警告: ${data.current_user} 正在${data.operation}`);
                }
                return data.success;
            } catch (error) {
                console.error('获取操作锁失败:', error);
                return false;
            }
        }

        // 释放操作锁
        async function releaseLock() {
            try {
                await fetch('/release_lock', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
            } catch (error) {
                console.error('释放操作锁失败:', error);
            }
        }

        // 上传包
        async function uploadPackage(fileInput, type) {
            if (!await acquireLock('上传文件')) {
                return;
            }
            
            try {
                const files = fileInput.files;
                console.log('uploadPackage 选择的文件 = ' + files.length);
                if (!files || files.length === 0) {
                    showStatus('请选择文件夹', true);
                    return;
                }

                const formData = new FormData();
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    // 保持文件的相对路径结构
                    const relativePath = file.webkitRelativePath;
                    formData.append('files', file, relativePath);
                }
                formData.append('type', type);
                console.log('开始上传文件 type =' + type + ' files = ' + files.length);

                try {
                    const response = await fetch('/upload', {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'Accept': 'application/json'
                        }
                    });                
                    const [packageType, buildType] = type.split('-');
                    const msgPrefix = `${packageType === 'chat' ? '聊天' : '人车生活'} ${buildType} 离线包上传`;
                    if (response.ok) {
                        const msg = `${msgPrefix}成功`;
                        showStatus(msg);
                        console.log(msg)
                        alert(msg);
                    } else {
                        const msg = `${msgPrefix}失败`;
                        console.log(msg)
                        throw new Error('上传失败');
                    }
                } catch (error) {
                    console.log('上传 error = ' + error);
                    showStatus('上传失败: ' + error.message, true);
                    alert('上传失败: ' + error.message);
                }
            } catch (error) {
                showStatus('上传失败: ' + error.message, true);
                alert('上传失败: ' + error.message);
            } finally {
                await releaseLock();
            }
        }        
        
        function uploadChatPackage(buildType) {
            const elementId = buildType === 'debug' ? 'chatPackageDebug' : 'chatPackageRelease';
            uploadPackage(document.getElementById(elementId), `chat-${buildType}`);
        }

        function uploadCarlifePackage(buildType) {
            const elementId = buildType === 'debug' ? 'carlifePackageDebug' : 'carlifePackageRelease';
            uploadPackage(document.getElementById(elementId), `carlife-${buildType}`);
        }        
        
        // 构建APK        
        async function unBuildApk() {
            try {
                const response = await fetch('/unbuild', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                if (response.ok) {
                    showStatus('已终止APK构建进程');
                } else {
                    const data = await response.json();
                    showStatus(data.error || '终止构建失败', true);
                }
            } catch (error) {
                showStatus('终止构建失败: ' + error.message, true);
            }
        }

        async function buildApk(buildType) {
            if (!await acquireLock('构建APK')) {
                return;
            }

            const buildButton = document.getElementById(`build${buildType.charAt(0).toUpperCase() + buildType.slice(1)}Button`);
            
            buildButton.disabled = true;
            showStatus(`正在构建${buildType === 'debug' ? '测试' : '正式'}APK...`);

            try {
                const response = await fetch('/build', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        chatPackageUploaded,
                        carlifePackageUploaded,
                        buildType
                    })
                });

                if (response.ok) {
                    showStatus('APK构建成功');
                    alert('APK构建成功');
                    // APK构建成功后不需要修改下载按钮状态，因为下载按钮始终可用
                } else {
                    throw new Error('构建失败');
                }
            } catch (error) {
                showStatus('构建失败: ' + error.message, true);
                alert('构建失败: ' + error.message);
            } finally {
                buildButton.disabled = false;
                await releaseLock();
            }
        }        // 页面加载完成后检查登录状态
        document.addEventListener('DOMContentLoaded', function() {
            const isLoggedIn = {{ 'true' if logged_in else 'false' }};
            if (!isLoggedIn) {
                document.getElementById('loginModal').classList.add('show');
            }
        });

        async function login() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            try {
                const response = await fetch('/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });

                const data = await response.json();
                
                if (response.ok) {
                    document.getElementById('loginModal').classList.remove('show');
                    showStatus('登录成功');
                } else {
                    document.getElementById('loginStatus').textContent = data.error || '登录失败';
                    document.getElementById('loginStatus').className = 'status error';
                }
            } catch (error) {
                document.getElementById('loginStatus').textContent = '登录失败: ' + error.message;
                document.getElementById('loginStatus').className = 'status error';
            }
        }        
        
        function downloadApk(buildType) {
            // 直接在新窗口打开下载链接，让浏览器处理下载
            console.log('开始执行 downloadApk 方法, buildType = ' + buildType);
            const url = `/download?buildType=${buildType}`;
            window.open(url, '_blank');
        }

        // 日志窗口拖动功能
        const logWindow = document.querySelector('.log-window');
        let isDragging = false;
        let currentX;
        let currentY;
        let initialX;
        let initialY;

        logWindow.addEventListener('mousedown', function(e) {
            if (e.target.classList.contains('log-content')) return;
            isDragging = true;
            initialX = e.clientX - logWindow.offsetLeft;
            initialY = e.clientY - logWindow.offsetTop;
        });

        document.addEventListener('mousemove', function(e) {
            if (!isDragging) return;
            
            e.preventDefault();
            currentX = e.clientX - initialX;
            currentY = e.clientY - initialY;
            
            // 确保窗口不会被拖出视口
            const maxX = window.innerWidth - logWindow.offsetWidth;
            const maxY = window.innerHeight - logWindow.offsetHeight;
            
            currentX = Math.max(0, Math.min(currentX, maxX));
            currentY = Math.max(0, Math.min(currentY, maxY));
            
            logWindow.style.left = currentX + "px";
            logWindow.style.top = currentY + "px";
            logWindow.style.right = "auto";
            logWindow.style.bottom = "auto";
        });

        document.addEventListener('mouseup', function() {
            isDragging = false;
        });
    </script>
</body>
</html>